package member

import (
	"adai.design/jarvis/common/db"
	"crypto/md5"
	"encoding/json"
	"fmt"
	"github.com/globalsign/mgo/bson"
	"io"
	"math/rand"
	"time"
)

type Account struct {
	Id    string `json:"uid" bson:"uid"`
	Phone string `json:"phone,omitempty" bson:"phone,omitempty"`
	Email string `json:"email,omitempty" bson:"email,omitempty"`
	Pwd   string `json:"password" bson:"password"`

	Name string `json:"name" bson:"name"`
	Icon string `json:"icon,omitempty" bson:"icon,omitempty"`

	RegDateStr string    `json:"registration_time" bson:"-"`
	RegDate    time.Time `json:"-" bson:"registration_time"`

	Homes []*Home `json:"homes,omitempty" bson:"homes,omitempty"`
}

// 用户与家庭的关系
const (
	RoleMaster = "master"
	RoleGuest  = "guest"
)

type Home struct {
	Id   string `json:"home" bson:"home"`
	Role string `json:"role" bson:"role"`
}

func (a *Account) String() string {
	a.RegDateStr = a.RegDate.Format("2006-01-02 15:04:05")
	buf, _ := json.Marshal(a)
	return string(buf)
}

func (a *Account) Account() string {
	if a.Phone != "" {
		return a.Phone
	} else {
		return a.Email
	}
}

func (a *Account) Save() error {
	session, err := db.GetSession()
	if err != nil {
		return err
	}
	defer session.Close()

	collection := session.DB("member").C("account")
	err = collection.Update(bson.M{"uid": a.Id}, a)
	return err
}

func (a *Account) sessionKey(devType string) string {
	t := time.Now()
	h := md5.New()
	io.WriteString(h, "adai.design")
	io.WriteString(h, t.String())
	io.WriteString(h, devType)
	io.WriteString(h, fmt.Sprintf("%x", rand.Int()))
	key := fmt.Sprintf("%x", h.Sum(nil))
	return key
}

// 查找已经登录的客户端
func (a *Account) findClients() *Clients {
	session, err := db.GetSession()
	if err != nil {
		return nil
	}
	defer session.Close()

	collection := session.DB("member").C("clients")
	var clients Clients
	err = collection.Find(bson.M{"uid": a.Id}).One(&clients)
	if err != nil {
		return nil
	}
	return &clients
}
